# -*- coding: UTF-8 -*-

from .models import BaseModel
from .addons_models import addons_models

from . import ui


class Environment(object):
    def __init__(self, rpc):
        self.rpc = rpc

    @property
    def context(self):
        return self.rpc.web.session.context

    def ref(self, xml_ref):
        module, xml_id = xml_ref.split('.')
        Model = self.model('ir.model.data')
        res = Model.call('check_object_reference', module, xml_id, True)
        model_name, res_id = res
        Model = self.model(model_name)
        return Model(res_id)

    def action_get(self, action_id, **kwargs):
        action = ui.Action(action_id, env=self, **kwargs)
        return action

    def treeview(self, action_id):
        return ui.TreeView(action_id, env=self)

    def formview(self, action_id):
        return ui.FormView(action_id, env=self)

    def field(self, field_info, **kwargs):
        view = ui.Field(field_info, env=self,  **kwargs)
        return view

    def relation(self, field_info, **kwargs):
        view = ui.Relation(field_info,  env=self,  **kwargs)
        return view

    def model(self, model, fields=None):
        return self._create_model_class(model, fields)

    def _create_model_class(self, model, fields):
        env1 = self

        addons_models2 = {}
        addons_models2.update(addons_models)
        addons_models2.update(self.rpc.addons_models)

        BaseModel2 = addons_models2.get(model, BaseModel)

        class MetaModel(BaseModel2):
            _env = env1
            _model = BaseModel2._model or model
            _fields = fields or {}

        return MetaModel
